<template>
  <div style="display: flex">
    <el-container>
      <div style="padding-top: 10px;padding-left: 10px;padding-right: 10px;" ref="headerHeight">
        <div class="report_header">
          <div class="report_header_left"></div>
          <div style="width: 100px;display: flex;align-items: center;margin-left: 10px;">
            <svg-icon class="primary" :icon-class="$route.meta.icon" />
            <span style="margin-left: 5px;" class="primary">{{$route.meta.title}}</span>
          </div>
          <div style="display: flex;flex-direction: row;justify-content: flex-end;width: 100%;">
            <div style="display: flex;flex-direction: row;flex-wrap: wrap;overflow: hidden;justify-content: flex-end;height: 41px;justify-content: flex-end;">
              <div class="report_header_date">
                <el-date-picker style="width: 100%" v-model="query.date" value-format="yyyy-MM-dd" type="daterange"
                  align="right" unlink-panels range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"
                  :picker-options="pickerOptions">
                </el-date-picker>
              </div>
              <div class="report_header_query" v-if="mchType==0||mchType==3">
                <el-select v-model="query.sysMchId" clearable placeholder="请选择商户"
                  filterable value-key="id" :filter-method="querySysmch" @change="changeSysMch">
                  <el-option v-for="item in mchIdOptions" :key="item.id" :label="item.name" :value="item.id">
                  </el-option>
                </el-select>
              </div>
              <div class="report_header_query">
                <el-select clearable v-model="value" placeholder="请选择状态">
                  <el-option label="待审核" :value="0"></el-option>
                  <el-option label="已审核" :value="1"></el-option>
                  <el-option label="已过期" :value="2"></el-option>
                </el-select>
              </div>
              <div class="report_header_query">
                <el-input prefix-icon="el-icon-search" placeholder="优惠券名" v-model="query.name"></el-input>
              </div>
            </div>
            <div style="display: flex;align-items: center;">
              <el-button style="margin-left: 10px;margin-top: 5px;" size="small" type="primary" @click="queryClick">查询</el-button>
              <el-button style="margin-left: 10px;margin-top: 5px;" size="small" type="primary" @click="addClick"
                v-permission="['coupon.add']">新增</el-button>
            </div>
          </div>
        </div>
      </div>
      <div class="pd10">
        <el-table :data="couponData" border stripe :height="curHeight" v-loadMore="[payLoads,'coupon-list']"
          @sort-change="sortChange" ref="table" style="width: 100%;">
          <el-table-column type="index" width="50" align="center" fixed>
          </el-table-column>
          <el-table-column align="center" prop="endDate" label="创建时间时间" sortable="custom" width="170">
            <template slot-scope="{row}">
              <span style="margin-left: 10px">{{row.createDate | datetimeFormatter}}</span>
            </template>
          </el-table-column>
          <el-table-column label="名称" align="left" prop="name" min-width="250">
          </el-table-column>
          <el-table-column label="类型" align="center" prop="type">
            <template slot-scope="{row}">
              {{ row.type | watchType}}
            </template>
          </el-table-column>
          <el-table-column label="适用范围" align="center" prop="scope">
            <template slot-scope="{row}">
              {{ row.scope | watchScope}}
            </template>
          </el-table-column>
          <el-table-column label="发行张数" align="right" prop="stock">
          </el-table-column>
          <el-table-column align="center" prop="beginDate" label="开始时间" sortable="custom" width="170">
            <template slot-scope="{row}">
              <span style="margin-left: 10px">{{row.beginDate | datetimeFormatter}}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="endDate" label="结束时间" sortable="custom" width="170">
            <template slot-scope="{row}">
              <span style="margin-left: 10px">{{row.endDate | datetimeFormatter}}</span>
            </template>
          </el-table-column>
          <el-table-column label="功能" width="80" align="center" fixed="right" v-permission="['coupon.audit']">
            <template slot-scope="scope">
              <el-button v-show="scope.row.status == 0" @click="releaseProduct(scope.row)" type="primary" size="mini">审核</el-button>
              <el-tag type="success" v-show="scope.row.status == 1">
                <span>已审核</span>
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" width="80" align="center">
            <template slot-scope="scope">
              <el-tooltip class="item" effect="dark" v-permission="['coupon.edit']" content="编辑" placement="top-start">
                <a @click="editClick(scope.row)">
                  <i style="color: #409EFF" class="el-icon-edit"></i>
                </a>
              </el-tooltip>
              <el-tooltip class="item" effect="dark" v-permission="['coupon.del']" content="删除" placement="top-start">
                <a style="margin-left: 10px" @click="deleteCoupon(scope.row)">
                  <i style="color: #F56C6C" class="el-icon-delete"></i>
                </a>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-footer class="el-footerBox">
        <pagination v-show="total>0" :total="total" :page.sync="pageNum" :limit.sync="pageSize" @pagination="loadCoupon"></pagination>
      </el-footer>
      <!--      <div style="background-color: red;height: 100px;width: 210px" @click="test"></div>-->
      <examine ref="examine" @loadCoupon="loadCoupon"></examine>

      <!--      <canvas id="myCanvas" width="500" height="500" style="border:1px solid #c3c3c3;position: fixed">-->

      <!--      </canvas>-->

    </el-container>
  </div>
</template>
<script>
  import loadMore from '@/utils/loadMore.js'
  import permission from '@/directive/permission/index.js' // 权限判断指令
  import {
    list,
    del
  } from '@/api/coupon'
  import utils from '../../utils/utils.js'
  import {
    EventBus
  } from '@/api/eventBus'
  import Pagination from '@/components/Pagination';
  import examine from "./components/examine"
  import {
    getInfo,
    list as sysMchList
  } from '@/api/sysMch'
  export default {
    name: 'coupon-list',
    directives: {
      permission,
      loadMore
    },
    activated() {
      this.payLoads = new Date().getTime();
    },
    data() {
      return {
        pickerOptions: { //时间快捷选择
          shortcuts: [{
            text: '昨天',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }]
        },
        value: '',
        isShow: false,
        couponData: [],
        pageNum: 1,
        pageSize: 20,
        payLoads: '',
        total: 0,
        queryType: true,
        mchIdOptions: [],
        mchType: '',
        query: {
          sysMchId: '',
          date: [],
          name: '',
        },
        keyword: {
          date: [],
          name: '',
        },
        curHeight: null,
        excelData: [],
        direction: '',
        sortField: '',
        headerType: false
      }
    },
    created() {
      var _this = this
      this.loadMch()
      this.loadSysmch('')
      this.loadCoupon()
      EventBus.$on('coupon-add', res => { // 监听新增完毕
        // 更新列表数组
        _this.couponData.splice(0, 0, res)
      });
      EventBus.$on('coupon-edit', res => { // 监听新增完毕
        // 更新列表数组
        for (let i = 0; i < _this.couponData.length; i++) {
          if (_this.couponData[i].id == res.id) {
            this.$set(this.couponData, i, res)
          }
        }
      })
    },
    components: {
      examine,
      Pagination
    },
    mounted() {
      this.comeIn()
      this.beforeMount()
    },
    filters: {
      watchType(val) {
        if (val == 0) {
          return '满减'
        } else if (val == 1) {
          return '满折'
        } else if (val == 2) {
          return '满赠'
        } else if (val == 3) {
          return '兑换券'
        }
      },
      watchScope(val) {
        if (val == 0) {
          return '全场'
        } else if (val == 1) {
          return '店内'
        } else if (val == 2) {
          return '商城'
        }
      }
    },
    methods: {
      loadSysmch(query) {
        sysMchList({
          name: query
        }).then(res => {
          this.mchIdOptions = res.data.data.filter(val => {
            return val.mchType === 3 || val.mchType === 1
          })
        }).catch(err => {
          console.log(err)
        })
      },
      changeSysMch() {
        this.loadCoupon()
      },
      querySysmch(query) {
        this.loadSysmch(query)
      },
      loadMch() {
        getInfo().then(res => {
          this.mchType = res.data.mchType
        })
      },
      test() {
        var c = document.getElementById("myCanvas");
        var cxt = c.getContext("2d");
        var img = new Image()
        img.src = "http://rzico.oss-cn-shenzhen.aliyuncs.com/img/022-lesson.png"

        cxt.drawImage(img, 0, 0);
      },
      releaseProduct(data) {
        this.$refs.examine.editVisible = true
        this.$refs.examine.findCoupon(data.id)
      },
      beforeMount() {
        var _this = this
        window.onresize = () => {
          return (() => {
            var h = document.documentElement.clientHeight || document.body.clientHeight;
            this.curHeight = h - 174  //减去页面上固定高度height this.curHeight = h - 220 //减去页面上固定高度height
          })();
        };
      },
      comeIn() {
        var _this = this
        setTimeout(function() {
          var h = document.documentElement.clientHeight || document.body.clientHeight;
          _this.curHeight = h - 174 //减去页面上固定高度height this.curHeight = h - 220 //减去页面上固定高度height
          console.log(_this.curHeight)
        }, 1);
      },
      editClick(row) {
        this.$router.push({
          path: '/coupon/edit',
          query: {
            id: row.id
          }
        })
      },
      loadCoupon() {
        var _this = this
        if(utils.isNull(this.keyword.date)){
          this.keyword.date = []
        }
        if(utils.isNull(this.value)){
          this.value = ''
        }
        let params = new URLSearchParams();
        params.append('startDate', this.keyword.date.length > 0 ? this.keyword.date[0] : '');
        params.append('endDate', this.keyword.date.length > 0 ? this.keyword.date[1] : '');
        params.append('status', this.value)
        params.append('pageNum', _this.pageNum);
        params.append('mchId', this.query.sysMchId)
        params.append('pageSize', _this.pageSize);
        params.append('name', _this.keyword.name);
        params.append('sortField', _this.sortField);
        params.append('direction', _this.direction);
        list(params).then(response => {
          console.log(response)
          _this.couponData = response.data.data
          _this.total = response.data.total
        }).catch(error => {
          console.log('error!!')
        });
      },
      chooseClick() {
        var _this = this
        this.headerType = !this.headerType
        this.comeIn()
      },
      addClick() {
        this.$router.push({
          path: '/coupon/add'
        })
      },
      deleteCoupon(data) {
        console.log(data)
        var _this = this
        this.$confirm('确认删除?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          del(data.id).then(response => {
            console.log(response)
            if (response.type)
              // 更新列表数组
              _this.couponData.forEach(function(item, index) {
                if (item.id == data.id) {
                  _this.couponData.splice(index, 1)
                }
              })
          }).catch(error => {
            console.log('error!!')
          });
        }).catch(() => {});
      },
      queryClick() {
        this.keyword = this.query;
        this.pageNum = 1
        this.loadCoupon()
      },
      resetClick() {
        this.query.date = []
        this.value = '';
        this.query.name = '';
        this.keyword = this.query;
        this.pageNum = 1;
        this.loadCoupon()
      },
      // 表格排序
      sortChange(column) {
        console.log(column)
        this.sortField = column.prop;
        if (column.order == 'ascending') {
          this.direction = 'asc'
        } else {
          this.direction = 'desc'
        }
        this.loadCoupon()
      },
    }
  }
</script>

<style scoped>
  .el-footerBox {
    height: 50px !important;
    line-height: 50px !important;
    border-top: 1px solid #f2f2f2;
  }

  .app {
    background-color: rgba(248, 248, 248, 0.8);
  }

  /*  /deep/.el-headerBox {
    padding: 10px;
    height: 100% !important;
    padding-bottom: 0;
  } */

  .report_header {
    width: 100%;
    min-height: 40px;
    box-sizing: border-box;
    background-color: rgba(248, 248, 248, 0.8);
    display: flex;
    align-items: center;
    padding-bottom: 5px;
    position: relative;
    padding-left: 5px;
    padding-right: 5px;
  }


  .report_header_left {
    width: 5px;
    height: 100%;
    background-color: #409EFF;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
  }

  .report_header_date {
    box-sizing: border-box;
    margin-left: 10px;
    width: 250px;
    margin-top: 5px;
  }

  .report_header_query {
    margin-left: 10px;
    width: 180px;
    margin-top: 5px;
  }
</style>
